package com.stylefeng.guns.modular.front.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.stylefeng.guns.common.persistence.model.*;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.controller.FrontBaseController;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.exception.FrontException;
import com.stylefeng.guns.modular.flagglory.service.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 *
 * @author fengshuonan
 * @Date 2018-01-31 14:13:35
 */
@RestController
@RequestMapping("/front/gloryUser")
public class FrontGloryUserController extends FrontBaseController {
    private final static Logger _log = LoggerFactory.getLogger(FrontBaseController.class);

    @Autowired
    private IGloryUserService gloryUserService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IUserRateService userRateService;
    @Autowired
    private ISeasonService seasonService;
    @Autowired
    private IDivisionService divisionService;
    @Autowired
    private IRobotService robotService;
    private final String APPID = "wx17e2575fc8ad3393";
    private final String SECRET = "fe3cd9342ac8141be91fe7de254ec464";

    /**
     * @return
     */
    @RequestMapping(value = "/userRankingList", method = RequestMethod.GET)
    @ApiOperation(value = "获取个人排名", notes = "获取star排名前一百名的用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "isPersonal", value = "true 单位，false 区域", dataType = "boolean", paramType = "query", defaultValue = "true"),
            @ApiImplicitParam(name = "userId", value = "当前用户id", dataType = "int", paramType = "query", defaultValue = "1")})
    public Object rankingList(Boolean isPersonal, Integer userId) throws FrontException {
        JSONObject result = new JSONObject();
        List<Map<String, Object>> userList = null;
        if (!isPersonal) {
            userList = gloryUserService.selectUserList(null);
        } else {
            Department userDepartment = departmentService.getUserDepartment(userId);
            if (null != userDepartment) {
                userList = gloryUserService.selectUserList(userDepartment.getId());
            }
        }
        if (null != userList) {
            for (Map<String, Object> map : userList) {
                int star = Integer.parseInt(map.getOrDefault("star", 0).toString());
                Division division = divisionService.getDivision(star);
                map.put("divisionName", division.getName());
            }
        }

        result.put("userList", userList);
        return new SuccessTip(result);
    }

    @RequestMapping(value = "/departmentRankingList", method = RequestMethod.GET)
    @ApiOperation(value = "获取集体排名", notes = "获取star排名前十的部门信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "isDepartment", value = "true 单位，false 区域(选择区域时，userId可以为空)",
                    dataType = "boolean", paramType = "query", defaultValue = "true"),
            @ApiImplicitParam(name = "userId", value = "当前用户id", dataType = "int", paramType = "query", defaultValue = "1")})
    public Object departmentRankingList(Boolean isDepartment, Integer userId) throws FrontException {
        List<Map<String, Object>> departmentRankingList = null;
        if (isDepartment) {
            GloryUser user = gloryUserService.selectById(userId);
            Integer deptid = user.getDeptid();
            //获取上级部门
            Department department = departmentService.selectById(deptid);
            if (null != department) {
                departmentRankingList = departmentService.selectDepartmentListById(department.getPid());
            }
        } else {
            departmentRankingList = departmentService.selectDepartmentList();
        }
        JSONObject result = new JSONObject();
        result.put("departmentRankingList", departmentRankingList);
        return new SuccessTip(result);
    }

    /**
     * 用户详情
     */
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    @ApiOperation("获取用户详情")
    @ApiImplicitParam(name = "openId", value = "用户openid", dataType = "string", paramType = "query", defaultValue = "1")
    public Object getUserInfo(String openId) {
        Map<String, Object> map = gloryUserService.selectGloryUserInfo(openId);
        int deptid = (int) map.getOrDefault("deptid", 0);
        Department department = departmentService.selectById(deptid);
        Department pDepartment = null;
        String from = "";
        if (null != department) {
            from += department.getFullname();
            Integer pid = department.getPid();
            if (null != pid) {
                pDepartment = departmentService.selectById(pid);
                if(null != pDepartment){
                    from = pDepartment.getFullname() + from;
                    map.put("pDeptName", pDepartment.getFullname());
                }
            }
        }
        int win = (int) map.getOrDefault("win", 0);
        int total = (int) map.getOrDefault("total", 0);
        double rate = Math.round(win * 1.0 / total * 100);
        map.put("from", from);
        map.put("rate", rate);
        return new SuccessTip(map);
    }

    @RequestMapping(value = "/getUserInfoByUserId", method = RequestMethod.GET)
    @ApiOperation("获取用户详情")
    @ApiImplicitParam(name = "userId", value = "用户id", dataType = "int", paramType = "query", defaultValue = "1")
    public Object getUserInfoByUserId(Integer userId) {
        Map<String, Object> map = gloryUserService.selectGloryUserInfo(userId);
        int deptid = (int) map.getOrDefault("deptid", 0);
        Department department = departmentService.selectById(deptid);
        Department pDepartment = null;
        String from = "";
        if (null != department) {
            from += department.getFullname();
            Integer pid = department.getPid();
            if (null != pid) {
                pDepartment = departmentService.selectById(pid);
                if(null != pDepartment){
                    from = pDepartment.getFullname() + from;
                    map.put("pDeptName", pDepartment.getFullname());
                }
            }
        }
        int win = (int) map.getOrDefault("win", 0);
        int total = (int) map.getOrDefault("total", 0);
        double rate = Math.round(win * 1.0 / total * 100);
        map.put("from", from);
        map.put("rate", rate);
        return new SuccessTip(map);
    }

    @RequestMapping(value = "/getUserCategory", method = RequestMethod.GET)
    @ApiOperation("获取用户分类答题信息")
    @ApiImplicitParam(name = "userId", value = "用户id", dataType = "int", paramType = "query", defaultValue = "9")
    public Object getUserCategory(Integer userId) throws FrontException {
        JSONObject result = new JSONObject();
        Season defaultSeason = seasonService.getDefaultSeason();
        List<Map<String, Object>> list = userRateService.selectUserRatesByUserId(userId, defaultSeason.getId());
        for (Map<String, Object> map : list) {
            double rightnum = Double.parseDouble(map.get("rightnum").toString());
            double totalnum = Double.parseDouble(map.get("totalnum").toString());
            double rate = Math.round(rightnum / totalnum * 100);
            if (rate < 10d) {
                rate = 10d;
            }
            map.put("rate", rate);
        }
        result.put("userRates", list);
        return new SuccessTip(result);

    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ApiOperation(value = "用户注册", notes = "测试数据:{\n" +
            "  \"avatarUrl\": \"图片地址\",\n" +
            "  \"city\": \"城市\",\n" +
            "  \"country\": \"国家\",\n" +
            "  \"deptid\": 0,\n" +
            "  \"gender\": 0,\n" +
            "  \"nickname\": \"昵称\",\n" +
            "  \"openid\": \"123\",\n" +
            "  \"phone\": \"123123123\",\n" +
            "  \"province\": \"省份\",\n" +
            "  \"remarks\": \"备注\",\n" +
            "}")
    @ApiImplicitParam(name = "user", value = "用户信息（微信获取的信息）", dataType = "GloryUser", paramType = "GloryUser")
    public Object register(@RequestBody GloryUser user) throws Exception {
        if (user.getOpenid() == null) {
            throw new FrontException("参数异常！注册失败！");
        }
        gloryUserService.register(user);
        return new SuccessTip();
    }

    @RequestMapping(value = "/authentication", method = RequestMethod.GET)
    @ApiOperation("用户认证")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "int", paramType = "query", defaultValue = "9"),
            @ApiImplicitParam(name = "deptId", value = "部门id", dataType = "int", paramType = "query", defaultValue = "18"),
            @ApiImplicitParam(name = "code", value = "邀请码", dataType = "String", paramType = "query", defaultValue = "66378888"),
            @ApiImplicitParam(name = "realName", value = "真实姓名", dataType = "String", paramType = "query", defaultValue = "66378888"),
    })
    public Object authentication(@RequestParam(value = "userId") Integer userId,
                                 @RequestParam(value = "deptId") Integer deptId,
                                 @RequestParam(value = "code") String code,
                                 @RequestParam(value = "realName") String realName) throws Exception {
        gloryUserService.authentication(userId, deptId, code, realName);
        return new SuccessTip();
    }

    @RequestMapping(value = "/getOpenId", method = RequestMethod.GET)
    @ApiOperation("获取用户openId")
    @ApiImplicitParam(name = "jsCode", value = "jsCode", dataType = "string", paramType = "query", defaultValue = "9")
    public Object getOpenId(String jsCode) throws FrontException {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID + "&secret=" + SECRET + "&js_code=" + jsCode + "&grant_type=authorization_code";
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = null;
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity httpEntity = response.getEntity();
            String result = null;
            try {
                result = EntityUtils.toString(httpEntity);
            } catch (Exception e) {
                e.printStackTrace();
            }// 返回json格式：
            jsonObject = JSONObject.parseObject(result);
        }
        String errcode = jsonObject.getString("errcode");
        if(StringUtils.isNotBlank(errcode)){
            _log.error("获取openid失败,errcode:" + errcode,jsonObject);
        }
        return new SuccessTip(jsonObject);
    }

    @RequestMapping(value = "/getRobotInfo", method = RequestMethod.GET)
    @ApiOperation("获取机器人信息")
    @ApiImplicitParam(name = "robotId", value = "机器人id", dataType = "int", paramType = "query", defaultValue = "1")
    public Object getRobotInfo(Integer robotId) throws FrontException {
        Robot robot = robotService.selectById(robotId);
        JSONObject result = JSONObject.parseObject(JSON.toJSONString(robot));
        result.put("avatarUrl", result.get("headimgurl"));
        result.remove("headimgurl");
        return new SuccessTip(result);
    }
}
